/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package strategies;

import common.Application;
import common.ParamStorage;
import dao.Entity;
import dao.EntityDAO;
import dao.Property;
import database.DatabaseException;
import database.Validator;
import html.XHtmlFormatter;
import localization.Localization;
import parsers.InputParser;
import presentation.PresentationElement;
import templates.PresentationTemplate;
import templates.Template;

/**
 *
 * @author Alejandro
 */
public class SaveEntityStrategy implements Strategy {

    @Override
    public void execute(WebContext ctx) {
        XHtmlFormatter provider = ctx.getWebFormatter();
        ParamStorage storage = ctx.getParamStorage();
        //provider.writeP("center", this.getClass().getName());
        provider.startDiv("", "operationResult");
        short uid = Short.parseShort(storage.getParam("table-selection"));
        EntityDAO dao = new EntityDAO(uid);
        String primaryKey = "";
        Entity e = null;
        boolean isNew = true;
        if (storage.hasParam("save_primary_key")) {
            primaryKey = storage.getParam("save_primary_key");
            isNew = false;
            try {
                e = (Entity) dao.findByPrimaryKey(primaryKey);
            } catch (DatabaseException ex) {
            }
        } else {
            e = Entity.newInstance(uid);
        }

        Template t = Application.getInstance().getTemplate(uid);
        int errors = 0;

        if (e != null) {
            InputParser parser = new InputParser(storage);
            Iterable<PresentationElement> presentations = e.getPresentationCollection();
            Validator v = new Validator();
            for (PresentationElement pe : presentations) {
                if (!e.isPrimaryKeyPresentation(pe)) {
                    String newValue = parser.parse(pe);
                    PresentationTemplate pt = pe.getTemplate();
                    Property p = e.getProperty(pt.getPropertyUid());
                    p.getValue().setValue(newValue);
                    if (!v.validate(p.getValue(), pt.getPropertyUid())) {
                        ++errors;
                        provider.putError(String.format(Localization.getString("FieldError"), Localization.getString(pt.getName()), v.getLastErrorDescription()));
                    }
                }
            }
            if (errors == 0) {
                try {
                    if (isNew) {
                        dao.create(e);
                        provider.putSuccess(Localization.getString("RowSaved"));
                    } else {
                        dao.update(e);
                        provider.putSuccess(String.format(Localization.getString("RowUpdated"), primaryKey));
                    }

                } catch (DatabaseException ex) {
                    if (isNew)
                        provider.putError(String.format(Localization.getString("FailedSave"), ex.getMessage()));
                    else
                        provider.putError(String.format(Localization.getString("FailedUpdate"), primaryKey, ex.getMessage()));
                }
            } else {
                ctx.setRedirect("/edit.jsp?validate-" + (isNew ? "add" : "edit") + "=");
            }
        }
        provider.endDiv();
    }
}
